package com.iap.common.service
{
	import com.iap.app.data.AppData;
	import com.iap.app.data.IAppData;
	import com.iap.app.model.ServiceResponse;
	import com.iap.common.event.ReportEvent;
	import com.iap.common.model.Report;
	import com.iap.common.translator.ReportTranslator;
	
	import org.robotlegs.mvcs.Actor;

	public class ReportService extends Actor implements IReportService
	{
		[Inject]
		public var data:IAppData;
		
		private var _task:String;
		public function set task(value:String):void { _task = value; }
		
		public function get(model:Report):void
		{
			if(model.id > 0)
			{
				data.dataComplete.add(responseHandler);
				data.load(this, model.id.toString());
			} else {
				getList();
			}
		}
		
		private function getList():void
		{
			data.dataComplete.add(responseHandler);
			data.load(this, AppData.JOB_GET);
		}
		
		public function save(model:Report):void
		{
			data.dataComplete.add(responseHandler);
			data.load(this, AppData.JOB_SAVE, model);
		}
		
		public function remove(model:Report):void
		{
			data.dataComplete.add(responseHandler);
			data.load(this, AppData.JOB_REMOVE, model);
		}
		
		private function responseHandler(response:ServiceResponse):void
		{
			data.dataComplete.remove(responseHandler);
			response.task = _task;
			response.result = ReportTranslator.translate(response.rawdata);
			dispatch(new ReportEvent(ReportEvent.RESPONSE, response));
		}
	}
}